<?php
namespace app\joybet\home;

use Braintree_Gateway;

/**
 *
 */
class Index extends Oauth
{

    // protected $access_token = 'access_token$sandbox$qwrbb244qxqbn6q7$b2ab845bfdbf87ef2911590dace1249a';
    protected $access_token = 'access_token$production$jwqc4w279qqbqpjw$e4d1ff1672b896fad177b03d54f53226';
    public function __construct()
    {
        parent::__construct();

        $this->member_info = model('joybet_member')->where(['id' => $this->uid])->find();
        $this->assign('member_info', $this->member_info);
    }
    
    public function index()
    {
        $game_id = input('id/d');
        $game = model('joybet_game')->find($game_id);

        // game is over
        if($game->status == 2){
            return $this->redirect('index/award', ['id' => $game_id]);
        }

        $player_list = model('joybet_order')->where(['game_id' => $game_id])->select();
        $joined = model('joybet_order')->where(['game_id' => $game_id, 'user_id' => $this->uid])->count();

        $this->assign([
            'joined' => $joined,
            'game' => $game,
            'player_list' => $player_list
        ]);

        return $this->fetch();
    }

    public function award()
    {
        $game_id = input('id/d');
        $game = model('joybet_game')->find($game_id);
        $player_list = model('joybet_order')->where(['game_id' => $game_id])->select();

        $this->assign([
            'game' => $game,
            'player_list' => $player_list
        ]);

        return $this->fetch();
    }

    public function joinHandler()
    {
        $game_id = input('game_id/d');
        $game = model('joybet_game')->find($game_id);
        $player_num = model('joybet_order')->where(['game_id' => $game_id])->count();

        if ($player_num >= $game->num) {
            return json(['err' => 1, 'msg' => 'This game is over']);
        }

        model('joybet_order')->save([
            'game_id' => $game_id,
            'user_id' => $this->uid,
            'name' => $this->member_info['name'],
            'picture' => $this->member_info['picture']
        ]);

        // last player joined, game is over
        if ($game->num - $player_num == 1) {
            $this->runGame($game_id, $game);
            return json(['err' => 0, 'data' => 'game over']);
        } else {
            return json(['err' => 0, 'data' => 'joined', 'msg' => 'Join successfully']);
        }
    }

    protected function runGame($game_id, $game)
    {
        $player_list = model('joybet_order')->where(['game_id' => $game_id])->select();
        $left_cash = $game->num * $game->amount;
        $left_num = $game->num;

        foreach ($player_list as $user) {
            if ($left_num > 1) {
                $float_cash = floor($left_cash / $left_num) - 100;
                $out_cash = 100 + mt_rand(0, 2 * $float_cash);
                $left_cash -= $out_cash;
                $left_num--;
            } else {
                $out_cash = $left_cash;
            }

            model('joybet_order')->save(['award' => $out_cash], ['id' => $user->id]);
        }

        return model('joybet_game')->save(['status' => 2], ['id' => $game_id]);
    }
    
    public function payment()
    {
        return $this->fetch();
    }

    public function startHandler()
    {
        $amount = input('amount/d');
        $num = input('num/d');

        if ($amount < 2 || $amount > 999 || $num < 2 || $num > 99) {
            return json(['err' => 1, 'msg' => 'invalid input']);
        }

        if ($this->member_info['amount'] < $amount) {
            return json(['err' => 1, 'msg' => 'insufficient funds']);
        }

        $game = model('joybet_game');
        $game->save([
            'host_id' => $this->uid,
            'name' => $this->member_info['name'],
            'picture' => $this->member_info['picture'],
            'amount' => $amount,
            'num' => $num
        ]);
        $game_id = $game->id;

        $member = model('joybet_member');
        $member->save(['amount' => ['exp', 'amount-'.$amount]], ['id' => $this->uid]);

        $order = model('joybet_order');
        $order->save([
            'game_id' => $game_id,
            'user_id' => $this->uid,
            'name' => $this->member_info['name'],
            'picture' => $this->member_info['picture'],
        ]);

        return json(['err' => 0, 'data' => $game_id]);
    }

    public function profile()
    {
         $gateway = new Braintree_Gateway(array(
            'accessToken' => $this->access_token,
         ));

        $clientToken = $gateway->clientToken()->generate();
        $this->assign([
            'clientToken' => $clientToken,
            'uid' => $this->uid
        ]);

        return $this->fetch();
    }

    public function withdraw()
    {
        $payouts = new \PayPal\Api\Payout();
        halt($payouts);
    }

    public function notify()
    {
        $amount = input('amount/f');
        $nonce = input('nonce');
        $uid = input('uid/d');

        $gateway = new Braintree_Gateway(array(
            'accessToken' => $this->access_token,
         ));

        $result = $gateway->transaction()->sale([
        "amount" => $amount,
        'merchantAccountId' => 'USD',
        "paymentMethodNonce" => $nonce,
        // "orderId" => $_POST['Mapped to PayPal Invoice Number'],
        // "descriptor" => [
        // "name" => "Descriptor displayed in customer CC statements. 22 char max"
        // ],
        // "shipping" => [
        // "firstName" => "Jen",
        // "lastName" => "Smith",
        // "company" => "Braintree",
        // "streetAddress" => "1 E 1st St",
        // "extendedAddress" => "Suite 403",
        // "locality" => "Bartlett",
        // "region" => "IL",
        // "postalCode" => "60103",
        // "countryCodeAlpha2" => "US"
        // ],
        // "options" => [
        // "paypal" => [
        // "customField" => $_POST["PayPal custom field"],
        // "description" => $_POST["Description for PayPal email receipt"]
        // ],
        // ]
        ]);

        if ($result->success) {
            model('joybet_member')->save(['amount' => ['exp', 'amount+' . $amount]], ['id' => $uid]);
            return json(['err' => 0, 'data' => $this->member_info['amount'] + $amount, 'msg' => '支付成功:账户增加$' . $amount]);
        } else {
            return json(['err' => 1, 'msg' => '支付失败:' . $result->message]);
        }
    }
}
